package com.leetcode.剑指offer第2版;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 覃国强
 * @date 2022-03-16 18:24
 */
public class 剑指Offer_58_I_翻转单词顺序 {

  static
  class Solution {
    public String reverseWords(String s) {
      if (s == null || s.length() == 0) {
        return "";
      }
      List<String> words = new ArrayList<>();
      StringBuilder sb = new StringBuilder();
      for (char ch : s.toCharArray()) {
        if (ch == ' ') {
          if (sb.length() > 0) {
            words.add(sb.toString());
            sb = new StringBuilder();
          }
        } else {
          sb.append(ch);
        }
      }
      if (sb.length() > 0) {
        words.add(sb.toString());
      }
      if (words.isEmpty()) {
        return "";
      }
      sb = new StringBuilder(words.get(words.size() - 1));
      for (int i = words.size() - 2; i >= 0; --i) {
        sb.append(' ').append(words.get(i));
      }
      return sb.toString();
    }
  }

}
